<template>
  <view>
    <view class="example">
      <view class="img_view">
        <image v-if="tAdvertInfo" class="bg_image" :src="tAdvertInfo"></image>
        <!-- <image v-else class="bg_image" src="../../../pagesSub/static/images/h_banner@2x.png"></image> -->
      </view>
      <uni-forms :rules="rules" ref="valiForm2" :modelValue="valiFormData">
        <view class="personInfoView">
          <view class="image-contain">
            <view class="icon_line_green"></view>
            <h4 class="consultTitle" for="">
              <text style="color: #ff5100; font-size: 40rpx;">*</text>
              确诊疾病
            </h4>
            <uni-forms-item name="confirmedDisease">
              <uni-easyinput
                :inputBorder="false"
                class="textArea"
                type="textarea"
                maxlength="50"
                autoHeight
                v-model="valiFormData.confirmedDisease"
                placeholder="点击此处输入确诊疾病"
              />
              <view class="count">
                <text>{{ valiFormData.confirmedDisease.length }}/50</text>
              </view>
            </uni-forms-item>
          </view>
          <view class="image-contain">
            <view class="icon_line_green"></view>
            <h4 class="consultTitle" for="">
              <text style="color: #ff5100; font-size: 40rpx;">*</text>
              病情描述
            </h4>
            <uni-forms-item name="illnessConetxt">
              <uni-easyinput
                :inputBorder="false"
                class="textArea"
                autoHeight
                type="textarea"
                maxlength="200"
                v-model="valiFormData.illnessConetxt"
                placeholder="点击此处输入病情描述"
              />
              <view class="count">
                <text>{{ valiFormData.illnessConetxt.length }}/200</text>
              </view>
            </uni-forms-item>
          </view>
          <view class="image-contain">
            <view class="icon_line_green"></view>
            <h4 class="consultTitle" for="">
              <text style="color: #ff5100; font-size: 40rpx;">*</text>
              需要的帮助
            </h4>
            <uni-forms-item name="needHelpContent">
              <uni-easyinput
                :inputBorder="false"
                class="textArea"
                autoHeight
                type="textarea"
                maxlength="200"
                v-model="valiFormData.needHelpContent"
                placeholder="点击此处输入需要的帮助"
              />
              <view class="count">
                <text>{{ valiFormData.needHelpContent.length }}/200</text>
              </view>
            </uni-forms-item>
          </view>
          <view class="image-contain">
            <view class="icon_line_green"></view>
            <h4 class="consultTitle" for="">
              检查资料上传
              <text class="smallTips">选择或添加检查资料(最多九张)</text>
            </h4>
            <htz-image-upload
              :max="9"
              mediaType="image"
              name="file"
              :chooseNum="9"
              v-model="valiFormData.images"
              @imgDelete="ceshiImgDelete"
              @chooseSuccess="ceshiChooseSuccess"
            ></htz-image-upload>
          </view>
          <view class="card_content" v-if="type == 1">
            <view class="personal_info">
              <text class="specification gray_font">开具发票</text>
              <view
                class="specification"
                style="display: flex;"
                @click="toggle('bottom')"
              >
                <view v-if="valiFormData.isBill == 1">本次不开具发票</view>
                <view
                  v-if="valiFormData.isBill == 0 && valiFormData.billType == 1"
                >
                  普通发票-个人
                </view>
                <view
                  v-if="valiFormData.isBill == 0 && valiFormData.billType == 2"
                >
                  普通发票-公司
                </view>
                <image
                  style="width: 40rpx; height: 30rpx; margin-top: 5rpx;"
                  src="../../../pagesSub/static/images/icon_right_black.png"
                ></image>
              </view>
            </view>
            <view v-if="valiFormData.isBill == 0 && valiFormData.billType == 1">
              <view class="specification">
                发票抬头：{{ valiFormData.rise }}
              </view>
            </view>
            <view v-if="valiFormData.isBill == 0 && valiFormData.billType == 2">
              <view class="specification">
                发票抬头：{{ valiFormData.unitName }}
              </view>
              <view class="specification">
                纳税人识别号：{{ valiFormData.taxPayerNo }}
              </view>
            </view>
          </view>
          <uni-popup ref="popup" background-color="#fff" :mask-click="false">
            <view style="padding: 30rpx;">
              <view class="colse_content">
                <image
                  @click="closeinvoice"
                  style="width: 50rpx; height: 50rpx; float: right;"
                  src="../../../pagesSub/static/images/icon_close_gray.png"
                ></image>
              </view>

              <view class="personal_info">
                <text class="specification">发票类型</text>
                <text class="specification gray_font">普通发票</text>
              </view>
              <view class="personal_info">
                <text class="specification">开具发票</text>
                <view>
                  <switch
                    :checked="isChecked"
                    color="#4CCCBF"
                    style="margin-top: -8rpx; transform: scale(0.7);"
                    @change="changeInvoice"
                  />
                </view>
              </view>
              <view v-if="valiFormData.isBill == 0">
                <text class="specification">发票抬头</text>
                <view class="invoice">
                  <view
                    style="margin-right: 15rpx;"
                    :class="valiFormData.billType == 1 ? 'tag' : ''"
                    @click="invoiceType(1)"
                    class="bth_green"
                  >
                    个人
                  </view>
                  <view
                    :class="valiFormData.billType == 2 ? 'tag' : ''"
                    @click="invoiceType(2)"
                    class="bth_green"
                  >
                    公司
                  </view>
                </view>
                <view class="invoiceInput" v-if="valiFormData.billType == 1">
                  <view style="display: flex;">
                    <view
                      style="
                        color: #ff5100;
                        font-size: 40rpx;
                        margin-right: 5rpx;
                      "
                    >
                      *
                    </view>
                    <uni-easyinput
                      style="width: 100%;"
                      v-model="valiFormData.rise"
                      placeholder="请填写开具发票人的姓名"
                    ></uni-easyinput>
                  </view>
                </view>
                <view class="invoiceInput" v-if="valiFormData.billType == 2">
                  <view>
                    <view style="display: flex;">
                      <view
                        style="
                          color: #ff5100;
                          font-size: 40rpx;
                          margin-right: 5rpx;
                        "
                      >
                        *
                      </view>
                      <uni-easyinput
                        style="width: 100%;"
                        v-model="valiFormData.unitName"
                        placeholder="请填写单位名称"
                      ></uni-easyinput>
                    </view>
                  </view>
                  <view style="margin-top: 20rpx;">
                    <view style="display: flex;">
                      <view
                        style="
                          color: #ff5100;
                          font-size: 40rpx;
                          margin-right: 5rpx;
                        "
                      >
                        *
                      </view>
                      <uni-easyinput
                        style="width: 100%;"
                        type="number"
                        v-model="valiFormData.taxPayerNo"
                        placeholder="请填写纳税人识别号"
                      ></uni-easyinput>
                    </view>
                  </view>
                </view>
              </view>
              <button @click="saveinvoiced" class="btn_invoice" type="default">
                确定
              </button>
            </view>
          </uni-popup>
        </view>
      </uni-forms>
      <view class="">
        <button
          type="primary"
          :disabled="disabledSave"
          class="positionfixed_btn arc_button"
          style="background-color: #3cb4ff; margin-top: 60rpx;"
          @click="next('valiForm2')"
        >
          下一步
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { TOKENNAME, HTTP_REQUEST_URL, UIDNAME } from '@/config/app.js'
import store from '@/store'
import { saveConsult, saveConsultFree } from '@/api/consult.js'
import { getConsultAdvert } from '@/api/common.js'
import {
  openOrderSubscribe,
  openOrderPaySubscribe,
} from '@/utils/SubscribeMessage.js'
import htzImageUpload from '@/pagesSub/components/htz-image-upload/htz-image-upload.vue'
// import htzImageUpload from '@/components/htz-image-upload/htz-image-upload.vue'

export default {
  name: 'Consultation',
  components: {
    htzImageUpload,
  },
  data() {
    return {
      disabledSave: false,
      tAdvertInfo: '',
      valiFormData: {
        confirmedDisease: '',
        illnessConetxt: '',
        needHelpContent: '',
        doctorId: 0,
        patientId: 0,
        images: [],
        isBill: 1,
        billType: 1,
        rise: '',
        unitName: '',
        taxPayerNo: '',
      },
      type: 0, //问诊类型1付费问诊 2 免费义诊
      rules: {
        confirmedDisease: {
          rules: [
            {
              required: true,
              errorMessage: '确诊疾病不能为空',
            },
          ],
        },
        illnessConetxt: {
          rules: [
            {
              required: true,
              errorMessage: '病情描述不能为空',
            },
          ],
        },
        needHelpContent: {
          rules: [
            {
              required: true,
              errorMessage: '需要的帮助不能为空',
            },
          ],
        },
      },
    }
  },
  onLoad(option) {
    this.getAdvertInfos()
    let item = JSON.parse(decodeURIComponent(option.item))
    // console.log(item,'患者信息')
    this.valiFormData.patientId = item.patientId
    this.type = item.type //问诊类型1付费问诊 2 免费义诊
    // console.log(this.valiFormData.patientId,'patientIdid')
    // console.log(serviceUidCache,'缓存中的医生id')
	if(item.doctorId>0){
		this.valiFormData.doctorId = item.doctorId
	}else{
		let serviceUidCache = store.state.app.serviceUid
		this.valiFormData.doctorId = serviceUidCache
	}
	console.log(this.valiFormData.doctorId,'doctorId')
  },
  methods: {
    //保存发票
    saveinvoiced() {
      let _this = this
      if (_this.valiFormData.isBill == 0 && _this.valiFormData.billType == 1) {
        if (_this.valiFormData.rise == '') {
          uni.showToast({
            title: '请填写发票抬头',
            icon: 'none',
            duration: 3000,
          })
          return
        }
      }
      if (_this.valiFormData.isBill == 0 && _this.valiFormData.billType == 2) {
        if (
          _this.valiFormData.unitName == '' ||
          _this.valiFormData.taxPayerNo == ''
        ) {
          uni.showToast({
            title: '请填写发票信息',
            icon: 'none',
            duration: 3000,
          })
          return
        }
      }

      this.$refs.popup.close()

      // console.log("&&&&发票信息",JSON.stringify(_this.valiFormData))
    },
    // 开具发票按钮
    changeInvoice(e) {
      if (e.target.value) {
        this.valiFormData.isBill = 0
      } else {
        this.valiFormData.isBill = 1
      }
    },
    invoiceType(type) {
      this.valiFormData.billType = type
      if ((type = 2)) {
        this.valiFormData.rise = ''
      }
      if ((type = 1)) {
        this.valiFormData.unitName = ''
        this.valiFormData.taxPayerNo = ''
      }
    },
    closeinvoice() {
      let _this = this
      if (_this.valiFormData.isBill == 0 && _this.valiFormData.billType == 1) {
        if (_this.valiFormData.rise == '' || _this.valiFormData.rise == null) {
          uni.showToast({
            title: '请填写发票抬头',
            icon: 'none',
            duration: 3000,
          })
          return
        }
      }
      if (_this.valiFormData.isBill == 0 && _this.valiFormData.billType == 2) {
        if (
          _this.valiFormData.unitName == '' ||
          _this.valiFormData.unitName == null ||
          _this.valiFormData.taxPayerNo == '' ||
          _this.valiFormData.taxPayerNo == null
        ) {
          uni.showToast({
            title: '请填写发票信息',
            icon: 'none',
            duration: 3000,
          })
          return
        }
      }

      this.$refs.popup.close()
    },
    toggle(type) {
      // open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
      this.$refs.popup.open(type)
    },
    // 获取广告位
    getAdvertInfos() {
      // uni.showLoading({title: '加载中'});
      getConsultAdvert()
        .then((res) => {
          // console.log("*****广告位###",JSON.stringify(res.data))
          this.tAdvertInfo = res.data.img
          // uni.hideLoading();
        })
        .catch((err) => {
          console.log('错误#', res)
          uni.hideLoading()
        })
    },
    ceshiImgDelete(e) {
      // console.log('ceshiImgDelete', e)
      // console.log('删除后：',this.valiFormData.images)
    },
    ceshiChooseSuccess(tempFilePaths, e) {
      //选择图片返回
      // console.log('ceshiChooseSuccess', tempFilePaths, e);
      this.imgUpload(tempFilePaths)
    },
    imgUpload(tempFilePaths) {
      let _this = this
      uni.showLoading({
        title: '上传中',
      })
      console.log('imgUpload', tempFilePaths)
      let uploadImgs = []
      tempFilePaths.forEach((item, index) => {
        uploadImgs.push(
          new Promise((resolve, reject) => {
            // console.log(index, item)
            uni.uploadFile({
              // url: "http://59.110.49.173:8001/api/common/uploadImg?dir=ad", //仅为示例，非真实的接口地址
              // filePath: item,
              // name: 'file',
              url: HTTP_REQUEST_URL + 'wx/common/savePatientPicInfo',
              filePath: item,
              fileType: 'image',
              name: 'fileName',
              header: {
                [TOKENNAME]: store.state.app.token,
                uid: store.state.app.uid,
              },
              success: (res) => {
                uni.hideLoading()
                _this.$util.Prom(res.code, res.msg)
                // console.log('uploadFileRes', res)
                resolve(res)
                var _res = JSON.parse(res.data)
                if (_res.code == 200) {
                  _this.valiFormData.images.push(_res.data.url)
                }
              },
              fail: (err) => {
                uni.hideLoading()
                console.log(err)
                reject(err)
              },
              complete: () => {
                //uni.hideLoading();
              },
            })
          }),
        )
      })
      Promise.all(uploadImgs) //执行所有需请求的接口
        .then((results) => {
          uni.hideLoading()
        })
        .catch((res, object) => {
          uni.hideLoading()
        })
      console.log('valiFormData.images', this.valiFormData.images)
    },

    // 上传图片成功
    success(e) {
      console.log('上传成功')
    },
    next() {
      let _this = this
      let orderType = _this.type //问诊类型1付费问诊 2 免费义诊
      // 校验提示
      if (!(_this.valiFormData.patientId > 0)) {
        _this.$util.Tips({
          title: '您选择的就诊人无效，请重新选择！',
        })
        return
      }
      if (!(_this.valiFormData.doctorId > 0)) {
        _this.$util.Tips({
          title: '您选择的医生无效，请重新选择！',
        })
        return
      }
      if (!_this.valiFormData.confirmedDisease) {
        _this.$util.Tips({
          title: '请填写确诊疾病！',
        })
        return
      }
      if (!_this.valiFormData.illnessConetxt) {
        _this.$util.Tips({
          title: '请填写病情描述！',
        })
        return
      }
      if (!_this.valiFormData.needHelpContent) {
        _this.$util.Tips({
          title: '请填写需要的帮助！',
        })
        return
      }
      _this.disabledSave = true
      //			console.log('--------------测试重复提交')
      //问诊类型1付费问诊 2 免费义诊saveConsultFree
      if (orderType == 1) {
        // console.log("&&&&&&测试###",JSON.stringify(_this.valiFormData))
        openOrderPaySubscribe()
          .then((res) => {
            uni.showLoading({
              title: '加载中',
            })
            saveConsult(_this.valiFormData)
              .then((res) => {
                uni.hideLoading()
                _this.$util.Prom(res.code, res.msg)
                let id = res.data.id
                if (id) {
                  setTimeout(function () {
                    uni.redirectTo({
                      url: `./consulOrder?id=${id}`,
                    })
                  }, 2000)
                } else {
                  _this.disabledSave = false
                  uni.showToast({
                    title: '添加失败！',
                    icon: 'none',
                    duration: 3000,
                  })
                }
              })
              .catch((err) => {
                _this.disabledSave = false
                uni.hideLoading()
                _this.$util.Prom(500, err)
                console.log('err', err)
              })
          })
          .catch((err) => {
            uni.hideLoading()
            _this.disabledSave = false
            console.log(err)
          })
      } else if (orderType == 2) {
        // console.log("****2222222222")
        openOrderSubscribe()
          .then((res) => {
            uni.showLoading({
              title: '加载中',
            })
            saveConsultFree(_this.valiFormData)
              .then((res) => {
                uni.hideLoading()
                _this.$util.Prom(res.code, res.msg)
                //@todo 跳转到问诊记录页面
                setTimeout(function () {
                  uni.redirectTo({
                    url: `/pagesSub-My/my/inquiryList`,
                  })
                  // _this.disabledSave = false;
                }, 2000)
              })
              .catch((err) => {
                _this.disabledSave = false
                uni.hideLoading()
                _this.$util.Prom(500, err)
                console.log('err', err)
              })
          })
          .catch((err) => {
            uni.hideLoading()
            _this.disabledSave = false
            console.log(err)
          })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/static/css/style.css';
/deep/.uni-forms-item__inner[data-v-61dfc0d0] {
  border-bottom: 0;
}
/deep/.uni-easyinput__content-textarea.data-v-abe12412 {
  background-color: #f8f8f8;
  padding: 25rpx;
  border-radius: 15rpx;
  font-size: 30rpx;
}
.example {
  background-color: #fff;
  padding-bottom: 280rpx;
}
.img_view {
  padding: 0 30rpx;
}
.bg_image {
  width: 100%;
  height: 180rpx;
  position: relative;
}
.image-contain {
  margin-bottom: 30rpx;
  background-color: #fff;
  padding: 0 30rpx;
  position: relative;
}
.consultTitle {
  // font-weight: bold;
  padding: 30rpx 5rpx;
  font-size: 32rpx;
}
.smallTips {
  font-size: 30rpx;
  margin-left: 20rpx;
}

//个人简介
.personInfoView {
  background-color: #f6f4f5;
  .count {
    padding-right: 30rpx;
    font-size: 32rpx;
    color: #aaa;
    display: flex;
    justify-content: flex-end;
    margin-bottom: -30rpx;
    position: relative;
    top: -44rpx;
    left: -12rpx;
  }
}
.icon_line_green {
  height: 35rpx;
  padding: 4rpx;
  border-top-right-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
  background-color: #4fcbbf;
  position: absolute;
  left: 0;
  top: 31rpx;
}
.card_content {
  background-color: #ffffff;
  border-bottom: 30rpx solid #f6f4f5;
  padding: 30rpx;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
  border-radius: 10rpx;
}
.personal_info {
  display: flex;
  justify-content: space-between;
}
.specification {
  font-size: 30rpx;
  margin-top: 10rpx;
}
.bth_green {
  border-top-right-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
  border-top-left-radius: 40rpx;
  border-bottom-left-radius: 40rpx;
  border: 1rpx solid #4cccbf;
  background-color: #ffffff;
  color: #4cccbf;
  height: 50rpx;
  line-height: 50rpx;
  font-size: 24rpx;
  padding: 0 25rpx;
}
.invoice {
  display: flex;
  margin: 10rpx 0;
}
.btn_invoice {
  color: #ffffff;
  background-color: #4ccdbc;
  font-size: 30rpx;
  margin-top: 60rpx;
  margin-bottom: 30rpx;
}
.invoiceInput {
  margin-top: 30rpx;
}
.tag {
  color: #ffffff !important;
  background-color: #4cccbf !important;
}
/deep/.uni-easyinput__content-input.data-v-abe12412 {
  font-size: 30rpx;
}
.colse_content::after {
  display: block;
  clear: both;
  content: '';
}
</style>
